package com.disease.chronic.Component;

import com.disease.chronic.Config.HttpSessionConfig;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/indicator/update/{id}",configurator = HttpSessionConfig.class)
public class IndicatorWebSocket {

    private final static ConcurrentHashMap<String , Session> sessionPoll = new ConcurrentHashMap<>();

    String username;
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id){
        username = id;
        sessionPoll.put(id,session);

    }

    static public void sendMessage(String username,String indicatorName,String value){
        try {

            if(!sessionPoll.containsKey(username)||!sessionPoll.get(username).isOpen())
                return;
            sessionPoll.get(username).getBasicRemote().sendText(indicatorName+","+value);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
